package com.dg11185.nearshop.activity.shop;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.util.SparseArray;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.libs.utils.date.DateUtils;
import com.dg11185.nearshop.app.StaticData;
import com.dg11185.nearshop.db.entity.DbConstant;
import com.dg11185.nearshop.db.entity.LastUpdateTime;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.entity.Industry;
import com.dg11185.nearshop.net.request.GetAreaListRequest;
import com.dg11185.nearshop.net.request.GetIndustryListRequest;
import com.dg11185.nearshop.net.request.ShopData;
import com.dg11185.nearshop.net.request.ShopData.NetListener;
import com.dg11185.nearshop.net.response.GetAreaListResponse;
import com.dg11185.nearshop.net.response.GetIndustryListResponse;
import com.wlper.lib.view.ExpandableTab;
import com.wlper.lib.view.HorizontalExpandableList;
import com.wlper.lib.view.adapter.SimpleAdapterWithMarker;

/**
 * 
 * @author：Daibo
 * @time：2014-6-13 下午2:25:48
 */
public class ExpandTabHelper {

    private static final String AREA_PARENT_ID = "249";

    public static final String[] distance = new String[] { "500 米", " 2 千米", " 5 千米", "10 千米" };

    /** 筛选栏View */
    private ExpandableTab mExpandTabView;

    private Activity mActivity;

    private ExpandTabListener listener;

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    /** 筛选栏需要的变量list和array用于显示，map用于获取id */
    /** 保存字段{@link Industry#name} **/
    private ArrayList<String> viewIndustryList = new ArrayList<String>();

    /** 保存字段{@link Area#name} **/
    private ArrayList<String> viewAreasList = new ArrayList<String>();

    private SparseArray<List<String>> viewIndustryArray = new SparseArray<List<String>>();

    private SparseArray<List<String>> viewAreaArray = new SparseArray<List<String>>();

    /** key-{@link Industry#name}, value{@link Industry#industryId} **/
    private HashMap<String, String> viewIndustryMap = new HashMap<String, String>();

    /** key-{@link Area#name}, value{@link Area#areaNum} **/
    private HashMap<String, String> viewAreaMap = new HashMap<String, String>();

    private HorizontalExpandableList areaFilter, industryFilter;

    private HorizontalExpandableList.ExpandableListAdapter areaAdapter, industryAdapter;

    public ExpandTabHelper(Activity activity, ExpandTabListener listener) {

        this.mActivity = activity;
        this.listener = listener;
        initCategoryView();
    }

    public HashMap<String, String> getAreaMap() {
        return viewAreaMap;
    }

    public HashMap<String, String> getIndustryMap() {
        return viewIndustryMap;
    }

    /**
     * 初始化筛选栏View
     */
    public void initCategoryView() {
        mExpandTabView = (ExpandableTab) mActivity.findViewById(R.id.ex_tab_v_shop_filters);

        mExpandTabView.addTabButton("全城", R.drawable.icon_region_filters);
        mExpandTabView.addTabButton("全部分类", R.drawable.icon_type_filters);
        mExpandTabView.addTabButton("离我最近", R.drawable.icon_sort_filters);
        mExpandTabView.setTitleStyle(15, R.color.font_black);
        mExpandTabView.setTabPadding(10, 0, 20, 0);
        // mExpandTabView.setDrawablePadding(30);

        // 区域选择视图

        areaFilter = new HorizontalExpandableList(mActivity);
        areaAdapter = new HorizontalExpandableList.ExpandableListAdapter(viewAreasList, viewAreaArray);
        areaFilter.setAdapter(areaAdapter);
        areaFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal, R.color.ex_list_selected);
        areaFilter.setHorizontalDivier(R.color.white);
        areaFilter.setOnItemSelectedListener(new HorizontalExpandableList.OnItemSelectedListener() {

            @Override
            public void onItemSelected(View itemView, String itemName, int itemPos1, int itemPos2) {
                updateTabView(0, replace(itemName, "全城"));
                // ************区域选择的事件添加如下*****************//
                listener.onTabSelectedChange(0, itemName, new int[] { itemPos1, itemPos2 });
            }
        });
        mExpandTabView.setDropView(0, areaFilter, true);

        // 商家类型选择视图
        industryFilter = new HorizontalExpandableList(mActivity);
        industryAdapter = new HorizontalExpandableList.ExpandableListAdapter(viewIndustryList, viewIndustryArray);
        industryFilter.setAdapter(industryAdapter);
        industryFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal,
                R.color.ex_list_selected);
        // industryFilter.setHorizontalDivier(R.color.white);
        industryFilter.setOnItemSelectedListener(new HorizontalExpandableList.OnItemSelectedListener() {

            @Override
            public void onItemSelected(View itemView, String itemName, int itemPos1, int itemPos2) {
                updateTabView(1, replace(itemName, "全部分类"));
                // ************商家类型选择的事件添加如下*****************//
                listener.onTabSelectedChange(1, itemName, new int[] { itemPos1, itemPos2 });
            }
        });
        mExpandTabView.setDropView(1, industryFilter, true);

        // 排序视图
        ListView sortFilter = new ListView(mActivity);
        List<Map<String, Object>> sortData = new ArrayList<Map<String, Object>>();
        SimpleAdapterWithMarker sortAdapter = new SimpleAdapterWithMarker(mActivity, sortData,
                StaticData.getSortFirLevCatalog(), R.layout.view_expand_tab_list_item, new String[] { "itemName" },
                new int[] { R.id.txt_v_item_name });
        sortAdapter.setItemBackground(R.color.ex_list_normal, R.color.ex_list_selected);
        sortAdapter.setItemClickListener(new SimpleAdapterWithMarker.OnItemViewClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TextView t = (TextView) view.findViewById(R.id.txt_v_item_name);
                updateTabView(2, replace(t.getText().toString(), "智能排序"));
                // ************排序方法选择的事件添加如下*************//
                listener.onTabSelectedChange(2, t.getText().toString(), new int[] { -1, -1 });
            }
        });
        sortFilter.setAdapter(sortAdapter);
        mExpandTabView.setDropView(2, sortFilter, false);

        System.out.println("after initview" + DateUtils.getCurTimeMinus());
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    public OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(mActivity, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    /**
     * 获取筛选栏数据，包括数据库获取和网络获取两部分
     */
    public void initCategoryDBData() {
        System.out.println("begin init data" + DateUtils.getCurTimeMinus());
        final Dao<LastUpdateTime, Integer> lastUpdateTimeDao = getHelper().getLastUpdateTimeDao();
        final Dao<Industry, Integer> industryDao = getHelper().getIndustryDao();
        final Dao<Area, Integer> areaDao = getHelper().getAreaDao();

        boolean isIndustryValid = DbConstant.isDataValid(lastUpdateTimeDao, DbConstant.INDUSTRY,
                DbConstant.INDUSTRY_UPDATE_TIME);
        boolean isAreaValid = DbConstant.isDataValid(lastUpdateTimeDao, DbConstant.AREA, DbConstant.AREA_UPDATE_TIME);
        if (isIndustryValid) {
            try {// 数据有效、从数据库中加载
                initIndustryViewData(industryDao.queryForAll());
                industryFilter.setAdapter(industryAdapter);
                industryFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal,
                        R.color.ex_list_selected);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } else {
            GetIndustryListRequest request = new GetIndustryListRequest();
            request.setActionListener(new GetIndustryListRequest.ActionListener<GetIndustryListResponse>() {

                @Override
                public void onSuccess(final GetIndustryListResponse result) {
                    System.out.println("IndustryListener success:" + result.industries.size());
                    if (result.industries.size() > 0) {
                        /** 初始化数据，更新filter */
                        initIndustryViewData(result.industries);
                        industryFilter.setAdapter(industryAdapter);
                        industryFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal,
                                R.color.ex_list_selected);
                        /** 新建线程刷新数据库 */
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (databaseHelper != null) {
                                    if (databaseHelper.isOpen()) {
                                        DbConstant.updataTable(industryDao, lastUpdateTimeDao, result.industries,
                                                DbConstant.INDUSTRY);
                                    }
                                }
                            }
                        }).start();
                    }
                }

                @Override
                public void onFailure(int resultCode) {

                }
            });
            NetClient.httpGet(mActivity, request);
        }
        if (isAreaValid) {
            try {// 数据有效、从数据库中加载
                initAreaViewData(areaDao.queryForAll());
                areaFilter.setAdapter(areaAdapter);
                areaFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal,
                        R.color.ex_list_selected);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            GetAreaListRequest request = new GetAreaListRequest(AREA_PARENT_ID);
            request.setActionListener(new GetAreaListRequest.ActionListener<GetAreaListResponse>() {

                @Override
                public void onSuccess(final GetAreaListResponse result) {
                    System.out.println("AreaListener success:" + result.areas.size());
                    if (result.areas.size() > 0) {
                        initAreaViewData(result.areas);
                        areaFilter.setAdapter(areaAdapter);
                        areaFilter.setItemBackground(HorizontalExpandableList.BOTH, R.color.ex_list_normal,
                                R.color.ex_list_selected);
                        /** industrys已经有了合法数据 */
                        /** 新建线程刷新数据库 */
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (databaseHelper != null) {
                                    if (getHelper().isOpen()) {
                                        DbConstant.updataTable(areaDao, lastUpdateTimeDao, result.areas,
                                                DbConstant.AREA);
                                    }
                                }
                            }
                        }).start();
                    }
                }

                @Override
                public void onFailure(int resultCode) {

                }
            });
            NetClient.httpGet(mActivity, request);
        }
    }

    /**
     * 初始化行业筛选栏的数据，它在两个时候被调用
     * 
     * 1、从数据库获得了有效的{@link ShopFragment#industries}数据后调用，然后调用
     * {@link ShopFragment#initCatagoryView()}初始化筛选栏
     * 
     * 2、当数据库获取的{@link ShopFragment#industries}值无效，先调用
     * {@link ShopData#getIndustryList(NetListener)}
     * 获取网络数据，然后调用该方法初始化筛选栏数据，最后更新筛选栏的adapter
     */
    private void initIndustryViewData(List<Industry> industries) {

        if (industries.size() != 0) {
            viewIndustryList.add("不限");
            viewIndustryArray.put(0, new LinkedList<String>());
            for (Industry i : industries) {
                if ("".equals(i.fatherId)) {
                    viewIndustryList.add(i.name);
                    viewIndustryMap.put(i.name, i.industryId);
                }
            }
            for (int a = 1; a < viewIndustryList.size(); a++) {
                String name = viewIndustryList.get(a);
                LinkedList<String> sub = new LinkedList<String>();
                sub.add("全部");
                for (Industry i : industries) {
                    if (i.fatherId.equals(viewIndustryMap.get(name)))
                        sub.add(i.name);
                }
                viewIndustryArray.put(a, sub);
            }
            for (Industry i : industries) {
                viewIndustryMap.put(i.name, i.industryId); // 将所有的数据映射到HashMap
            }
        }
    }

    /**
     * 初始化行业筛选栏的数据，它在两个时候被调用
     * 
     * 1、从数据库获得了有效的{@link ShopFragment#areas}数据后调用，然后调用
     * {@link ShopFragment#initCatagoryView()}初始化筛选栏
     * 
     * 2、当数据库获取的{@link ShopFragment#areas}值无效，先调用
     * {@link ShopData#getAreaList(NetListener)}
     * 获取网络数据，然后调用该方法初始化筛选栏数据，最后更新筛选栏的adapter
     */
    private void initAreaViewData(List<Area> areas) {
        if (areas.size() != 0) {
            viewAreasList.add("全城");
            LinkedList<String> list = new LinkedList<String>();
            list.add("不限");
            for (String s : distance) {
                list.add(s);
            }
            viewAreaArray.put(0, list);
            for (int a = 0; a < areas.size(); a++) {
                viewAreaMap.put(areas.get(a).name, areas.get(a).areaNum);
                viewAreasList.add(areas.get(a).name);
                LinkedList<String> sub = new LinkedList<String>();
                viewAreaArray.put(a + 2, sub);
            }
        }
    }

    private String replace(String str, String repStr) {
        if (str.equals("不限") || str.equals("全部")) {
            return repStr;
        }
        return str;
    }

    /**
     * 隐藏下拉窗口
     * 
     * @return 隐藏成功的话返回true，否则返回false
     */
    public boolean hideDropWindow() {
        if (mExpandTabView != null)
            return mExpandTabView.hideDropdownWindow();
        return false;
    }

    /**
     * 刷新筛选栏
     * 
     */
    public void updateTabView(int position, String showText) {
        hideDropWindow();
        mExpandTabView.setTitle(position, showText);
    }

    public void releseDBHelper() {
        /*
         * You'll need this in your class to release the helper when done.
         */
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }

    }

    public interface ExpandTabListener {
        public void onTabSelectedChange(int id, String txt, int[] position);
    }
}
